import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.swing.JOptionPane;

import java.util.*;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.sql.*;
import java.text.*;
import java.util.Date;
import java.text.*;
import java.util.*;
import java.awt.image.BufferedImage;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.imageio.ImageIO;

import java.io.*;

import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.ImageInputStream;

import util.MyConnection;

import java.net.*;
import java.awt.Graphics2D;
import java.util.zip.*;

public class download extends HttpServlet {

	String desktopPath1 = System.getProperty("user.home") + "/Desktop";
	String desktopPath = desktopPath1.replace("\\", "/");
	int resizlen;
	int hashcode;
	String filecontent = "";
	String fname = "";
	String sname = "";
	String snameid = "";
	String saveFile = "";
	String tempfilename = "";
	String mid = "";
	StringBuilder sb = new StringBuilder();
	String message2 = null;
	// String iplocation="/////Pondyit/java finised projects 2014/";
	// String iplocation1="/////Pondyit/java finised projects 2014/uploading1/";
	// String iplocation2="/////Pondyit/java finised projects 2014/uploading2/";
	// String iplocation3="/////Pondyit/java finised projects 2014/uploading3/";

	String iplocation = "D:/";
	String iplocation1 = "D:/uploading1/";
	String iplocation2 = "D:/uploading2/";
	String iplocation3 = "D:/uploading3/";

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		mid = (String) request.getParameter("fname");
		System.out.println(mid);
		HttpSession session = request.getSession();
		// sname=(String) session.getAttribute("name");
		snameid = (String) session.getAttribute("eid");
		sname = (String) session.getAttribute("name");
		// snameid="D@gmail.com";
		RequestDispatcher rp;
		String fname = "";

		java.io.File file101 = new File("D:/downloading");

		if (!file101.exists())
			file101.mkdirs();
		int lent = 0;
		FileInputStream fs = null;
		File fi = null;

		String dbname = "";
		call2(dbname = "message");
		sb.setLength(0);
		fname = saveFile;
		System.out.println(fname);
		// // for(int i=0;i<3;i++){
		// // call(i);
		// // }
		//
		// filecontent=sb.toString();
		//
		// int formDataLength = filecontent.length();
		// byte dataBytes[] =filecontent.getBytes();
		//
		//
		//
		saveFile = "D:/downloading/" + saveFile;
		//
		// File ff = new File(saveFile);
		// System.out.println(ff.toString());
		// ff.createNewFile();
		// FileOutputStream fileOut = new FileOutputStream(ff);
		// BufferedOutputStream bos = new BufferedOutputStream(fileOut);
		// bos.write(dataBytes);
		// bos.flush();
		// bos.close();

		String FILE_NAME = fname;

		FileOutputStream fos = null;
		FileInputStream fis;
		byte[] fileBytes;
		int bytesRead = 0;
		File ofile = new File(saveFile);
		List<File> list = new ArrayList<File>();
		list.add(new File(iplocation1 + FILE_NAME + snameid));
		list.add(new File(iplocation2 + FILE_NAME + snameid));
		list.add(new File(iplocation3 + FILE_NAME + snameid));

		try {

			fos = new FileOutputStream(ofile, true);
			for (File file : list) {
				fis = new FileInputStream(file);
				fileBytes = new byte[(int) file.length()];
				bytesRead = fis.read(fileBytes, 0, (int) file.length());
				assert (bytesRead == fileBytes.length);
				assert (bytesRead == (int) file.length());
				fos.write(fileBytes);
				fos.flush();
				fileBytes = null;
				fis.close();
				fis = null;
			}
			fos.close();
			fos = null;
		} catch (Exception e) {
			System.out.println("Error Occured");
			saveFile = iplocation + "uploading" + sname + "/" + fname;
			// fos = new FileOutputStream(saveFile,true);
			File file = new File(saveFile);
			fis = new FileInputStream(file);
			fileBytes = new byte[(int) file.length()];
			bytesRead = fis.read(fileBytes, 0, (int) file.length());
			assert (bytesRead == fileBytes.length);
			assert (bytesRead == (int) file.length());
			fos.write(fileBytes);
			fos.flush();
			fileBytes = null;
			fis.close();
			fis = null;
			fos.close();
			fos = null;
		}
		System.out.println("Downlaoded");
		callrate();
		rp = request.getRequestDispatcher("provider3.jsp?success=s");
		rp.forward(request, response);
	}

	private void callrate() {
		// TODO Auto-generated method stub
		// String download=null;
		int down = 0;
		try {

			Class.forName("com.mysql.jdbc.Driver");
			// Setup the connection with the DB

			// // Statements allow to issue SQL queries to the database
			// statement = connect.createStatement();
			// // Result set get the result of the SQL query
			// resultSet = statement
			// .executeQuery("select * from feedback.comments");
			// writeResultSet(resultSet);

			
			Statement s = MyConnection.getStatement();

			ResultSet rs = s.executeQuery("select * from rating where sid='"
					+ snameid + "'");
			// ResultSet rs11 =
			// s.executeQuery("select * from informationreg where productname='"+searchstr.toString().trim()+"'");

			if (rs.next()) {

				down = rs.getInt("download");
				// down=Integer.parseInt(download);

			}

			down = down + 1;
			// download=Integer.toString(down);
			rs.close();

			s.close();
		} catch (Exception e) {
			System.out.println("Exception is ;" + e);
		}

		try {
			DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
			Date date = new Date();
			String sss = date.toLocaleString();
			String active = "yes";
			int rs1;
			Statement s = MyConnection.getStatement();

			rs1 = s.executeUpdate("update rating SET download='" + down
					+ "' where sid='" + snameid + "'");

		} catch (Exception e1) {

			e1.printStackTrace();
		}

	}

	private void call(int j) {
		// TODO Auto-generated method stub
		String temppath = null;
		int i = 0;
		switch (j) {
		case 0:
			i = 0;
			call3(iplocation1, i);
			break;
		case 1:
			i = 1;
			call3(iplocation2, i);
			break;
		case 2:
			i = 2;
			call3(iplocation3, i);
			break;
		}
	}

	private void call3(String iplocation12, int i) {
		// TODO Auto-generated method stub
		BufferedReader br = null;

		try {

			String sCurrentLine = null;
			//
			// filecontent=null;
			sb.append("\n");
			System.out.println(iplocation12 + saveFile + ".part"
					+ Integer.toString(i));
			br = new BufferedReader(new FileReader(iplocation12 + saveFile
					+ sname + ".part" + Integer.toString(i)));

			while ((sCurrentLine = br.readLine()) != null) {
				// System.out.println(sCurrentLine);
				sb.append(sCurrentLine);
				sb.append("\n");

			}

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}
	}

	private void call2(String db) {
		// TODO Auto-generated method stub
		try {
			Statement s = MyConnection.getStatement();
			ResultSet rs = s.executeQuery("select * from " + db + " where id='"
					+ mid + "'");
			// ResultSet rs11 =
			// s.executeQuery("select * from informationreg where productname='"+searchstr.toString().trim()+"'");

			if (rs.next()) {

				saveFile = rs.getString("filename");
				saveFile = saveFile.trim();

			}

			rs.close();

			s.close();
		} catch (Exception e) {
			System.out.println("Exception is ;" + e);
		}
	}

}
